//
//  CustomAlertView.swift
//  iotSoundBox
//
//  Created by Lee on 2018/11/23.
//  Copyright © 2018年 Lee. All rights reserved.
//

import UIKit

class CustomAlertView: UIView {

    private var PWidth = CGFloat(0)
    private var PHeight = CGFloat(0)
    private var titleLabel:UILabel?
    private var messageLabel:UILabel?
    private var popWindow: UIWindow?
    private var popView: UIView?
    private var selectBtnAction: ((_ selectBtnTag:Int) -> ())?
    
//    var isViewEnabled: Bool?{
//        didSet{
//            self.isUserInteractionEnabled = isViewEnabled ?? false
//        }
//    }
    
    var isViewTap = false
  
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    /// <#Description#>
    ///
    /// - Parameters:
    ///   - frame: <#frame description#>
    ///   - title: <#title description#>
    ///   - message: <#message description#>
    ///   - contentArr: <#contentArr description#>
    ///   - width: <#width description#>
    ///   - btnDirection: <#btnDirection description#>
    ///   - selectBtnAction: <#selectBtnAction description#>
    public convenience init(frame: CGRect, title: String, message: String?, contentArr: NSArray, btnTitleColorArr: NSArray?, width: CGFloat, btnDirection:Int?, selectBtnAction: ((_ selectBtnTag:Int) -> ())?) {
        
        self.init(frame: frame)
        
        self.PWidth = width < 280 ? 280 : width
//        self.PHeight = self.PWidth - 80
        
        self.selectBtnAction = selectBtnAction
        
        setupSubviews(frame: frame, title: title, message: message, contentArr: contentArr, btnTitleColorArr:btnTitleColorArr, btnDirection:btnDirection)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupSubviews(frame: CGRect, title: String, message: String?, contentArr: NSArray,btnTitleColorArr: NSArray?, btnDirection:Int?) {
        
        let tHeight = self.getSize(font: UIFont.systemFont(ofSize: 17), textWidth: PWidth - 16, contentStr: title as NSString).height > 20 ? self.getSize(font: UIFont.systemFont(ofSize: 17), textWidth: PWidth - 16, contentStr: title as NSString).height : 20
        
        let mHeight = self.getSize(font: UIFont.systemFont(ofSize: 15), textWidth: PWidth - 16, contentStr: (message ?? "") as NSString).height > 20 ? self.getSize(font: UIFont.systemFont(ofSize: 15), textWidth: PWidth - 16, contentStr: (message ?? "") as NSString).height : 20
        
        
        self.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        self.frame = frame
        let popView = UIView.init()
        popView.backgroundColor = UIColor.white
//        popView.frame = CGRect(x: MainWidth/2 - PWidth/2, y: MainHeight/2 - PHeight/2, width: PWidth, height: PHeight)
        popView.layer.cornerRadius = 8
        popView.layer.masksToBounds = true
        self.addSubview(popView)
        self.popView = popView
        
        let titleTopHeight = CGFloat(message?.count == 0 || message == nil ? 25 : 15)
        let messageHeight = CGFloat(message?.count == 0 || message == nil ? 0 : mHeight)
        
        let titleLabel = UILabel.init(frame: CGRect(x: 8, y: titleTopHeight, width: PWidth - 16, height: tHeight))
        titleLabel.textColor = UIColor.black
        titleLabel.textAlignment = NSTextAlignment.center
        titleLabel.font = UIFont.systemFont(ofSize: 17)
        titleLabel.text = title
        titleLabel.numberOfLines = 0
        self.popView?.addSubview(titleLabel)
        self.titleLabel = titleLabel

        let messageLabel = UILabel.init(frame: CGRect(x: 8, y: titleLabel.n_maxY + 15, width: titleLabel.n_width, height: messageHeight))
        messageLabel.textColor = UIColor.darkGray
        messageLabel.textAlignment = NSTextAlignment.center
        messageLabel.font = UIFont.systemFont(ofSize: 15)
        messageLabel.text = message
        messageLabel.numberOfLines = 0
        self.popView?.addSubview(messageLabel)
        self.messageLabel = messageLabel
        
        let topHeight = message?.count == 0 || message == nil ? messageLabel.n_maxY + 10 : messageLabel.n_maxY + 15
        let btnHeight = CGFloat(55)
        for i in 0..<contentArr.count {
            let btn = UIButton.init(type: .custom)
            btn.frame = btnDirection == 0 || btnDirection == nil ? CGRect(x: 0, y: topHeight + btnHeight*CGFloat(i), width: PWidth, height: btnHeight) : CGRect(x: CGFloat(i)*(PWidth/CGFloat(contentArr.count)), y: topHeight , width: PWidth/CGFloat(contentArr.count), height: btnHeight)
            btn.setTitle((contentArr[i] as! String), for: UIControl.State.normal)
            let color = (btnTitleColorArr == nil ? UIColor.init(r: 44, g: 92, b: 200) : btnTitleColorArr?[i]) as! UIColor
            btn.setTitleColor(color, for: UIControl.State.normal)
            btn.tag = i
            btn.addTarget(self, action: #selector(btnClick(sender:)), for: UIControl.Event.touchUpInside)
            self.popView?.addSubview(btn)
            
            let lineView = UIView.init()
            lineView.frame = CGRect(x: 0, y: topHeight + btnHeight*CGFloat(i), width: PWidth, height: 0.5)
            lineView.backgroundColor = BORADCOLOR
            self.popView?.addSubview(lineView)
            
            if contentArr.count != 0 && btnDirection != 0 && btnDirection != nil {
                let verLineView = UIView.init()
                verLineView.frame = CGRect(x: CGFloat(contentArr.count - 1)*PWidth/CGFloat(contentArr.count), y: topHeight, width: 0.5, height: btnHeight)
                verLineView.backgroundColor = BORADCOLOR
                self.popView?.addSubview(verLineView)
            }
        }
        
        self.PHeight = btnDirection == 0 || btnDirection == nil ? topHeight + btnHeight*CGFloat(contentArr.count) : topHeight + btnHeight
        popView.frame = CGRect(x: MAINWIDTH/2 - PWidth/2, y: MAINHEIGHT/2 - PHeight/2, width: PWidth, height: self.PHeight)
    }
    
    @objc private func btnClick(sender:UIButton) {
        
        if self.selectBtnAction != nil {
            self.selectBtnAction!(sender.tag)
        }
        self.dismissPopView()
    }
    
    func alertViewChangeAttribute() {
        
        if isViewTap == true {
            let tap = UITapGestureRecognizer.init(target: self, action: #selector(dismissPopView))
            tap.delegate = self
            self.addGestureRecognizer(tap)
        }
    }
    
    func showPopView() {
        
        self.alertViewChangeAttribute()
        
        let popWindow = UIWindow.init(frame: MAINSCREEN)
        popWindow.windowLevel = UIWindow.Level.alert
        popWindow.becomeKey()
        popWindow.makeKeyAndVisible()
        popWindow.addSubview(self)
        self.popWindow = popWindow
        self.popWindow?.isHidden = false
        
//        self.showAnimation()
    }
    
    private func showAnimation() {
        
        UIView.animate(withDuration: 0, delay: 0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
            
            self.popView?.layer.setValue(0, forKeyPath: "transform.scale")
            
        }) { (finished:Bool) in
            
            UIView.animate(withDuration: 0.23, delay: 0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
                
                self.popView?.layer.setValue(1.2, forKeyPath: "transform.scale")
                
            }) { (finished:Bool) in
                
                UIView.animate(withDuration: 0.09, delay: 0.02, options: UIView.AnimationOptions.curveEaseInOut, animations: {
                    
                    self.popView?.layer.setValue(0.9, forKeyPath: "transform.scale")
                    
                }) { (finished:Bool) in
                    
                    UIView.animate(withDuration: 0.05, delay: 0.02, options: UIView.AnimationOptions.curveEaseInOut, animations: {
                        
                        self.popView?.layer.setValue(1, forKeyPath: "transform.scale")
                        
                    }) { (finished:Bool) in
                        
                    }
                }
            }
        }
    }
    
    @objc public func dismissPopView() {
        
        self.removeFromSuperview()
        self.popWindow!.resignKey()
        self.popWindow!.isHidden = true
    }
}

extension CustomAlertView:UIGestureRecognizerDelegate {
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {

        if touch.view!.isDescendant(of: self.popView!) {
            return false
        }
        return true
    }
}
